<template>
  <div class="bmks">
    <div class="w">
      <div class="container" ref="container">
        <div class="top clearfix">
          <el-breadcrumb separator-class="el-icon-arrow-right" class="fl">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>管理部门</el-breadcrumb-item>
          </el-breadcrumb>
          <div class="btns fr">
            <el-button v-if="isAdmin" class="seat" type="warning" @click="$router.push({name: 'seat'})">管理座位</el-button>
            <el-button v-if="isAdmin" class="admin" type="primary" @click="$router.push({name: 'admin'})">管理员工</el-button>
            <el-button v-if="isLogin && Authcode!=101" class="personal" type="info" @click="$router.push({name: 'personal'})">个人信息</el-button>
            <el-button v-if="isLogin" type="danger" class="loginOut" @click="outLogin">退出</el-button>
          </div>
        </div>

        <!-- 顶部搜索 -->
        <el-col :span="24" class="header-op" style="height: 62px;">
          <el-form :inline="true">
            <!-- <el-form-item>
              <el-select v-model="condition.bm" placeholder="部门" @change="changeDepartment" @clear="clearD" style="max-width=200px">
                <el-option v-for="(item,index) in options.department" :key="index" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="condition.ks" placeholder="科室" @clear="goSearch">
                <el-option v-for="(item,index) in options.section" :key="index" :label="item.secname" :value="item.secname">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="搜索" v-model="condition.searchText" clearable @keyup.enter.native="goSearch" @clear="goSearch">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="goSearch" icon="el-icon-search"></el-button>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" plain @click="addBmks('d')" v-if="Authcode == 101">新增部门</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="danger" plain @click="delSelections">批量删除</el-button>
            </el-form-item> -->
            <!-- <el-form-item>
            <el-button type="danger" plain>批量冻结</el-button>
          </el-form-item> -->
            <!-- <el-form-item>
            <el-button type="success" plain>批量解冻</el-button>
          </el-form-item> -->

          </el-form>
        </el-col>

        <!-- 表格内容 -->
        <el-table v-loading="loading" class="bumen" stripe :max-height="tableHeight" :data="initData.list" :header-cell-style="{'background-color': '#e8ecf1','color': '#0d2d84'}" :row-style="{'padding': '0px'}" :cell-style="{'padding': '5px'}" :row-key="getRowKeys" :expand-row-keys="expands" @expand-change="exChange" @row-click="toggleRowExpansion">

          <!-- <el-table-column align="center" type="selection" width="55"></el-table-column> -->
          <el-table-column align="center" header-align='center' label="部门名称" prop="department_name"></el-table-column>
          <!-- <el-table-column align="center" header-align='center' label="部门" prop="department" width="150"></el-table-column> -->
          <el-table-column align="center" header-align='center' label="科室数量" width="150">
            <template slot-scope="scope">
              {{scope.row.section.length}}
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" header-align='center' label="职务" prop="position" width="160">
          </el-table-column> -->

          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template slot-scope="scope">
              <div class="buttons">
                <el-button title="查看科室" @click="showDetail(scope)" type="primary" size="mini" icon="el-icon-view"></el-button>
                <el-button title="编辑部门" @click="changeData(scope.row)" size="mini" icon="el-icon-edit"></el-button>
                <el-button title="删除" v-if="Authcode == 101" @click="deleteData(scope.row)" type="danger" size="mini" icon="el-icon-delete"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-show="this.initData.total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="params.pageSize" :current-page="params.page" :page-sizes="pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="initData.total">
        </el-pagination>
      </div>

      <!-- 查看科室 -->
      <el-dialog :visible.sync="dialog.keshi" width="500px" @close="closeKeshi">
        <template slot="title">
          <div class="title">查看科室</div>
        </template>
        <el-table :data="initData.detail" style="width: 100%" max-height="450px">
          <el-table-column align="center" header-align='center' label="科室名称" prop="secname"></el-table-column>

          <el-table-column label="操作" align="center" width="140" fixed="right">
            <template slot-scope="scope">
              <div class="buttons">
                <el-button @click="changeData2(scope.row)" size="mini" icon="el-icon-edit"></el-button>
                <el-button v-if="Authcode == 101 || Authcode == 201" @click="deleteData(scope.row)" type="danger" size="mini" icon="el-icon-delete"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-button class="add-ks" type="primary" plain @click="addBmks('s')">新增科室</el-button>
        </div>
      </el-dialog>

      <!-- 编辑部门/科室 -->
      <el-dialog :visible.sync="dialog.add_edit" width="500px">
        <template slot="title">
          <div class="title">{{((key)=>{
            switch(key){
              case 0: return `新增${editData.dors == 'd'?'部门':'科室'}`;break;
              case 1: return `编辑${editData.dors == 'd'?'部门':'科室'}`;break;
            }
            })(editData.mode)}}</div>
        </template>
        <div class="name-input">
          <span>{{editData.dors == 'd'?'部门':'科室'}}名称: </span>
          <el-input v-model="editData.name" placeholder="请输入名称"></el-input>
        </div>
        <div class="btns">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button plain @click="dialog.add_edit = false">取消</el-button>
        </div>
      </el-dialog>

    </div>

  </div>
</template>

<script>
export default {
  name: 'bmks',
  data() {
    return {
      tableHeight: 0,
      isLogin: false,
      isAdmin: false,
      loading: false,
      lockD: true,
      lockS: true,
      pageSizes: [5, 10, 15, 20, 50, 100],
      initData: {
        list: [],
        // current: 1,
        total: 0,
        detail: [],
      },
      params: {
        page: 1,
        pageSize: 10,
        searchText: "",
        department: '',
        section: '',

      },
      options: {
        department: [],
        section: [],
        section2: [],
        authcode: [
          {
            label: "超级管理员",
            value: 101
          },
          {
            label: "部门管理员",
            value: 201
          },
          {
            label: "科室管理员",
            value: 301
          },
          {
            label: "无",
            value: 401
          }
        ]
      },
      condition: {
        bm: '',
        ks: '',
        searchText: '',
      },
      dialog: {
        keshi: false,
        add_edit: false,
      },
      editData: {
        mode: 0,
        id: 0,
        name: '',
        dors: 'd'
      },
      department_id: 0,
      department_index: -1,
      section: {},
      // 要展开的行，数值的元素是row的key值
      expands: [],
    }
  },
  created() {
    this.init();
    this.getUserInfo();
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = this.$refs.container.offsetHeight - 205;
      // console.log(this.$refs.container.offsetHeight)
      // console.log(this.tableHeight)
    })
  },
  computed: {
    Authcode() {
      return this.$cookies.get("__ac")
    },
    Token() {
      return this.$cookies.get("__tk")
    },
  },
  methods: {
    // 初始化列表
    init() {
      this.axios({
        method: 'GET',
        url: '/api/dpsinfo/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        params: { username: this.$cookies.get('__un') }
      }).then(res => {
        // console.log('dps res==>', res)
        if (res.data.code == 200) {
          let obj = res.data.data;
          for (let k in obj) {
            this.options.department.push({
              value: obj[k].department_name,
              id: obj[k].department_id,
              chlidren: obj[k].section
            })
          }
          this.initData.list = obj;
          // console.log('dpsinfo==>', this.options.department)
          if (this.department_index != -1) {
            let i = this.department_index;
            this.initData.detail = this.initData.list[i].section;
            // this.department_index = -1;
          }
        } else {
          this.$message.warning('请询问超级管理员');
        }
      }).catch(error => {
        // console.log('error==>', error)
        this.loading = false;
        this.$message.error(error || "出现错误，请稍后再试")
      })
    },
    // 获取用户数据
    getUserInfo() {
      let tokenString = this.$cookies.get("__tk");
      this.authorizeCode = this.$cookies.get("__ac");
      if (!tokenString) {
        this.isLogin = false;
        this.$router.push('/home')
      } else {
        this.isLogin = true;
      }
      if (this.authorizeCode == 101 || this.authorizeCode == 301 || this.authorizeCode == 201) {
        this.isAdmin = true;
        if (this.authorizeCode == 301) {
          this.lockD = false;
          this.lockS = false;
        } else if (this.authorizeCode == 201) {
          this.lockD = false;
          this.lockS = true;
        }
      } else {
        this.isAdmin = false;
        this.$router.push('/home')
      }
      // console.log('登录状态==>', this.isLogin)
      // console.log('管理状态==>', this.isAdmin)

    },
    // 退出
    outLogin() {
      if (this.isLogin) {
        
        this.isLogin = false;
        this.isAdmin = false;
        this.$message.success('退出成功');
        setTimeout(() => {
          this.$router.push({ name: 'home' });
        }, 500);
      } else {
        return
      }
    },
    // 部门-科室联动
    changeDepartment() {
      this.condition.ks = '';
      for (const i in this.options.department) {
        if (this.options.department[i].value == this.condition.bm) {
          this.options.section = this.options.department[i].chlidren;
        }
      }
    },
    // 清空部门
    clearD() {
      this.condition.section = '';
      this.options.section = '';
      this.goSearch();
    },
    // 搜索请求
    search() {
      // console.log("发起搜索请求");
      if (this.loading) {
        return
      }
      this.loading = true;// 加载显示
      this.axios({
        method: 'POST',
        url: '/api/data_auth_search/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        data: this.$qs.stringify({
          username: this.$cookies.get('__un'),
          authcode: this.$cookies.get('__ac'),
          page: this.params.page,
          perpageitem: this.params.pageSize,
          department: this.params.department,
          section: this.params.section,
          searchText: this.params.searchText,
        })
      }).then(res => {
        // console.log('search res==>', res)
        if (res.data.code == 100) {
          this.initData.list = res.data.data.personinfo;
          this.initData.total = res.data.data.pageinfo.totalnum;
          // console.log('search list==>', this.initData.list)
          // this.$message({
          //   message: '查询成功',
          //   type: 'success'
          // });
        } else {
          this.$message.error('查询失败');
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        // console.log('error==>', error)
        this.$message.error(error || "出现错误，请稍后再试")
      })

    },
    // 改变搜索条件
    goSearch() {
      this.params.page = 1;
      this.params.department = this.condition.bm;
      this.params.section = this.condition.ks;
      this.params.searchText = this.condition.searchText;
      this.search();
    },
    // 新增部门
    addBmks(t) {
      this.editData = {
        mode: 0,
        id: 0,
        name: '',
        dors: t
      }
      this.dialog.add_edit = true;
    },
    // 查看
    showDetail(o) {
      this.department_index = o.$index;
      // console.log('index ==>', this.department_index)
      this.initData.detail = o.row.section;
      this.department_id = o.row.department_id;
      this.editData.dors = 's';
      this.dialog.keshi = true;
    },
    // 关闭查看
    closeKeshi() {
      this.editData.dors = 'd';
      this.department_index = -1;
    },
    // 编辑-部门
    changeData(o) {
      this.editData = {
        mode: 1,
        id: o.department_id,
        name: o.department_name,
        dors: 'd'
      }
      this.dialog.add_edit = true;
    },
    // 编辑-科室
    changeData2(o) {
      this.editData = {
        mode: 1,
        id: o.section_id,
        name: o.secname,
        dors: 's'
      }
      this.dialog.add_edit = true;
    },
    // 删除
    deleteData(o) {
      let text = '';
      if (this.editData.dors == 'd') {
        text = `该操作不可逆${o.section.length > 0 ? '（该部门存在科室）' : ''}`;
      } else {
        text = `该操作不可逆`
      }
      this.$confirm(`${text}, 是否确认删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios({
          method: 'delete',
          url: '/api/dpsinfo/',
          headers: {
            'Token': this.$cookies.get('__tk')
          },
          data: { dors: this.editData.dors, id: o.department_id ? o.department_id : o.section_id }
        }).then(res => {
          // console.log('res==>', res)
          if (res.data.code == 200) {
            this.$message.success(res.data.msg)
            this.init();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(error => {
          // console.log('error==>', error)
          this.$message.error(error || "出现错误，请稍后再试")
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 新增/编辑提交
    submit() {
      if (this.editData.name != '') {
        if (this.editData.mode == 0) {
          // 新增请求
          let data = {};
          if (this.editData.dors == 'd') {
            data = {
              dors: this.editData.dors,
              department: this.editData.name,
            }
          } else {
            data = {
              dors: this.editData.dors,
              department_id: this.department_id,
              section: this.editData.name,
            }
          }
          // console.log('add data==>', data)
          this.axios({
            method: 'put',
            url: '/api/dpsinfo/',
            headers: {
              'Token': this.$cookies.get('__tk')
            },
            data: data
          }).then(res => {
            // console.log('add res==>', res);
            if (res.data.code == 100) {
              this.$message.success('新增成功')
              this.dialog.add_edit = false;
              this.init();  
            } else {
              this.$message.error('新增失败')
            }
          }).catch(error => {
            // console.log('error==>', error);
            this.$message.error(error || "出现错误，请稍后再试");
          })

        } else {
          // 编辑请求
          let data = {};
          if (this.editData.dors == 'd') {
            data = {
              id: this.editData.id,
              dors: this.editData.dors,
              department: this.editData.name,
            }
          } else {
            data = {
              id: this.editData.id,
              dors: this.editData.dors,
              section: this.editData.name,
            }
          }
          // console.log('编辑请求-------', data)
          this.axios({
            method: 'post',
            url: '/api/dpsinfo/',
            headers: {
              'Token': this.$cookies.get('__tk')
            },
            data: this.$qs.stringify(data)
          }).then(res => {
            // console.log('edit res==>', res);
            if (res.data.code == 100) {
              this.$message.success('编辑成功')
              this.dialog.add_edit = false;
              this.init();
            } else {
              this.$message.error('编辑失败')
            }
          }).catch(error => {
            // console.log('error==>', error);
            this.$message.error(error || "出现错误，请稍后再试");
          })
        }
      } else {
        this.$message.warning("请输入名称");
        return false;
      }
    },
    // 获取row的key值
    getRowKeys(row) {
      return row.id;
    },
    // 点击箭头展开一行
    exChange(row, rowList) {
      // console.log('exChange==>', rowList)
      if (rowList.length) { // 只展开一行//说明展开了
        // console.log('expands==>', this.expands)
        if (this.expands.length) {
          if (this.expands[0] == row.id) {
            this.expands = [];// 同一行则收起
          } else {
            this.expands = []
            this.expands.push(row.id)// 展开另一行
          }
        } else {
          this.expands.push(row.id)// 只展开当前行id
        }
      } else { // 说明收起了
        this.expands = []
      }
    },
    // 点击行展开一行
    toggleRowExpansion(row) {
      if (this.expands.length) {
        if (this.expands[0] == row.id) {
          this.expands = [];// 同一行则收起
        } else {
          this.expands = []
          this.expands.push(row.id)// 展开另一行
        }
      } else {
        this.expands.push(row.id)// 只展开当前行id
      }
    },
    // 当前页
    handleCurrentChange(p) {
      this.params.page = p;
      this.search()
    },
    // 条/页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pageSize = val;
      this.search();
    },
    // 多选
    handleSelectionChange(v) {
      this.multipleSelection = v;
    },
  },
}
</script>

<style lang="scss" scoped>
.bmks {
  background-color: #fff;
  .container {
    padding: 20px;
    background-color: #fff;
    border-radius: 6px;
    height: calc(100% - 40px);
    .top {
      padding-bottom: 10px;
      margin-bottom: 10px;
      border-bottom: 1px solid #ccc;
      >>> .el-breadcrumb {
        font-size: 20px;
        height: 40px;
        line-height: 40px;
      }
    }
    .header-op {
      height: 62px;
      .el-select,
      .el-input {
        max-width: 200px;
      }
    }
    >>> .el-table {
      margin-bottom: 10px;
      // .el-table__expanded-cell[class*="cell"] {
      //   padding: 0px 20px;
      // }
    }
    >>> .el-pagination {
      text-align: center;
    }
  }
  >>> .el-dialog {
    .title {
      font-size: 20px;
      height: 20px;
      line-height: 1;
      text-align: center;
      font-weight: bold;
      color: #000;
    }
    .el-dialog__body {
      padding-top: 10px;
      position: relative;
      .add-ks {
        position: absolute;
        top: -30px;
        left: 10px;
      }
      .name-input {
        > span {
          height: 40px;
          line-height: 40px;
          display: inline-block;
          margin-right: 15px;
        }
        .el-input {
          width: 380px;
        }
      }
      .btns {
        text-align: center;
        margin-top: 20px;
        .el-button {
          width: 100px;
          & + .el-button {
            margin-left: 50px;
          }
        }
      }
    }
  }
}
</style>